import { Controller, Post, Req, UnauthorizedException, HttpCode, Inject } from '@nestjs/common';
import type { Request } from 'express';
import { AuthService } from './auth.service';
import { AuthConfig } from './auth.config';

@Controller('auth')
export class AuthController {
  constructor(
    @Inject(AuthService) private readonly authService: AuthService,
  ) {}

  @Post('refresh-token')
  @HttpCode(200)
  async refreshToken(@Req() request: Request) {
    // 从 Cookie 中获取刷新令牌
    const refreshToken = request.cookies?.[AuthConfig.refreshTokenCookie.name];
    
    if (!refreshToken) {
      throw new UnauthorizedException('刷新令牌不存在');
    }
    
    try {
      // 使用刷新令牌生成新的访问令牌
      const newAccessToken = await this.authService.refreshAccessToken(refreshToken);
      
      // 返回新的访问令牌
      return {
        access_token: newAccessToken
      };
    } catch (error) {
      throw new UnauthorizedException('刷新令牌已过期或无效');
    }
  }
}